package com.example.springboot.controller;


import com.baomidou.mybatisplus.core.conditions.query.Query;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.py.mymodule.submodule.common.Result;
import org.py.mymodule.submodule.entity.*;
import org.py.mymodule.submodule.mapper.CommodityMapper;
import org.py.mymodule.submodule.mapper.OrdersMapper;
import org.py.mymodule.submodule.mapper.OrdersTailsMapper;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author author
 * @since 2024-08-13
 */
@RestController
@RequestMapping("/orders")
public class OrdersController {
    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private OrdersTailsMapper ordersTailsMapper;

    @Autowired
    private CommodityMapper commodityMapper;
  //  订单的生成
    @PostMapping("/create")
    public Result createOrder(@RequestBody Orderscommoditys orderscommodity) {
        try {

            Orders orderss = ordersMapper.selectById(orderscommodity.getOrderId());
            QueryWrapper<OrdersTails> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("order_id",orderscommodity.getOrderId())
                    .eq("commodity_id",orderscommodity.getCommodityId());
            OrdersTails ordersTails1 = ordersTailsMapper.selectOne(queryWrapper);
            QueryWrapper<Commodity> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("commodity_name",orderscommodity.getCommodityName());
            Commodity commodity = commodityMapper.selectOne(queryWrapper1);
            if(ordersTails1!=null){
                return Result.error("该明细已存在");
            }
            if(orderss==null) {
                Orders orders = new Orders();
                orders.setOrderId(orderscommodity.getOrderId());
                orders.setOrderDate(LocalDateTime.now()); // 设置订单日期为当前时间
                orders.setOrderPrice(commodity.getCommodityPrice().multiply(new BigDecimal(orderscommodity.getCommodityquantity()))); // 设置订单价格
                orders.setOrderState("完成"); // 设置订单状态
                orders.setCostomerAddress(null); // 设置客户地址
                orders.setCostomerPhone(orderscommodity.getCostomerPhone()); // 设置客户电话
                OrdersTails ordersTails = new OrdersTails();
                ordersTails.setOrderId(orderscommodity.getOrderId());
                ordersTails.setCommodityId(orderscommodity.getCommodityId());
                ordersTails.setCommodityQuantity(orderscommodity.getCommodityquantity());
                ordersMapper.insert(orders); // 插入订单数据
                ordersTailsMapper.insert(ordersTails); // 插入订单明细数据
                return Result.success();
            }
            else {//修改订单的总价
                orderss.setOrderPrice(orderss.getOrderPrice().add(orderscommodity.getCommodityPrice().multiply(new BigDecimal(orderscommodity.getCommodityquantity()))));
                ordersMapper.updateById(orderss);
                OrdersTails ordersTails = new OrdersTails();
                ordersTails.setOrderId(orderscommodity.getOrderId());
                ordersTails.setCommodityId(orderscommodity.getCommodityId());
                ordersTails.setCommodityQuantity(orderscommodity.getCommodityquantity());
                ordersTailsMapper.insert(ordersTails);
                return Result.success();
            }
        }
        catch (Exception e) {
            // 处理异常，例如记录日志或返回错误信息
            return Result.error();
        }
    }
// 订单的修改
//    @PutMapping("/update")
//    public Result updateOrder(@RequestBody Orderscommodity orderscommodity){
//        try{
//            Orders orderss = ordersMapper.selectById(orderscommodity.getOrderId());
//            QueryWrapper<OrdersTails> queryWrapper = new QueryWrapper<>();
//            queryWrapper.eq("order_id",orderscommodity.getOrderId())
//                    .eq("commodity_id",orderscommodity.getCommodityId());
//            OrdersTails ordersTails = ordersTailsMapper.selectOne(queryWrapper);
//            Commodity commodity = commodityMapper.selectById(orderscommodity.getCommodityId());
//
//    }


//
//    //订单的查询
//
//    @GetMapping("/query/{orderId}")
//    public Orders queryOrder(@PathVariable("orderId") Long orderId) {
//        return ordersMapper.selectById(orderId);
//    }

    @PutMapping("/update")
    public Result updateorder(@RequestBody Orderscommoditys orderscommoditys) {
        // 开始事务
      try{
            // 查询订单
            QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("order_id", orderscommoditys.getOrderId());
            Orders orders = ordersMapper.selectOne(queryWrapper);
            if (orders == null) {
                return Result.error("Order not found");
            }

            // 查询订单明细
            QueryWrapper<OrdersTails> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("order_id", orderscommoditys.getOrderId()).eq("commodity_id", orderscommoditys.getCommodityId());
            OrdersTails ordersTails = ordersTailsMapper.selectOne(queryWrapper1);
            if (ordersTails == null) {
                return Result.error("Order details not found");
            }

            // 查询商品
            Commodity commodity = commodityMapper.selectById(orderscommoditys.getCommodityId());
            if (commodity == null) {
                return Result.error("Commodity not found");
            }

            // 更新订单价格
            BigDecimal commodityPrice = commodity.getCommodityPrice();
            BigDecimal quantity1 = new BigDecimal(ordersTails.getCommodityQuantity());
            BigDecimal quantity2 = new BigDecimal(orderscommoditys.getCommodityquantity());

            BigDecimal newOrderPrice = orders.getOrderPrice()
                    .subtract(commodityPrice.multiply(quantity1))
                    .add(commodityPrice.multiply(quantity2));

            orders.setOrderPrice(newOrderPrice);
            // 更新客户电话
            orders.setCostomerPhone(orderscommoditys.getCostomerPhone());

            // 更新订单尾表
            ordersTails.setCommodityQuantity(orderscommoditys.getCommodityquantity());
            ordersTails.setCommodityId(orderscommoditys.getCommodityId());

            // 更新数据库
            ordersMapper.updateById(orders);
            ordersTailsMapper.updateById(ordersTails);

            // 返回更新后的订单对象
            return Result.success();
        } catch (Exception e) {
            return Result.error("修改失败");
        }
    }


    //界面：订单查询按id
    @GetMapping("/getorder/{id}")
    public List<Orderscommodity> getcommodity(@PathVariable("id") Integer id) {
        try {
            Orders orders = ordersMapper.selectById(id);
            if (orders == null) {
                return new ArrayList<>();
            }

            QueryWrapper<OrdersTails> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("order_id", id);
            List<OrdersTails> ordersTails = ordersTailsMapper.selectList(queryWrapper);


            if (ordersTails.isEmpty()) {
                return Collections.emptyList();
            }

            List<Integer> commodityIds = ordersTails.stream()
                    .map(OrdersTails::getCommodityId)
                    .collect(Collectors.toList());

            List<Commodity> commodities = commodityMapper.selectBatchIds(commodityIds);
            List<Orderscommodity> orderscommodities = new ArrayList<>();
            for (Commodity commodity : commodities) {
                QueryWrapper<OrdersTails> queryWrapper1 = new QueryWrapper<>();
                queryWrapper1.eq("commodity_id", commodity.getCommodityId())
                        .eq("order_id", orders.getOrderId());
                OrdersTails ordersTails1 = ordersTailsMapper.selectOne(queryWrapper1);
                Orderscommodity orderscommodity = new Orderscommodity(orders.getOrderDate(),orders.getOrderId(),commodity.getCommodityId(),orders.getCostomerPhone(),commodity.getCommodityName(),commodity.getCommodityPrice(),ordersTails1.getCommodityQuantity());
                orderscommodities.add(orderscommodity);
            }
            return orderscommodities;

        } catch (Exception e) {
            throw new RuntimeException("Error querying goods", e);
        }
    }

    //所有订单商品的查询
    @GetMapping("/getorderall")
    public List<Orderscommodity> getcommodityall(){
        try {
            List<Orders> orders = ordersMapper.selectList(null);
            if (orders == null) {
                return new ArrayList<>();
            }
            List<Orderscommodity> orderscommodities = new ArrayList<>();
            for(Orders orders1 : orders) {
                QueryWrapper<OrdersTails> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("order_id", orders1.getOrderId());
                List<OrdersTails> ordersTails = ordersTailsMapper.selectList(queryWrapper);

                List<Integer> commodityIds = ordersTails.stream()
                        .map(OrdersTails::getCommodityId)
                        .collect(Collectors.toList());
                // 确保commodityIds是一个Collection类型
                if (commodityIds.isEmpty()) {
                    continue; // 如果commodityIds为空，跳过当前循环
                }
                List<Commodity> commodities = commodityMapper.selectBatchIds(commodityIds);

                for (Commodity commodity : commodities) {
                    QueryWrapper<OrdersTails> queryWrapper1 = new QueryWrapper<>();
                    queryWrapper1.eq("commodity_id", commodity.getCommodityId())
                            .eq("order_id", orders1.getOrderId());
                    OrdersTails ordersTails1 = ordersTailsMapper.selectOne(queryWrapper1);
                    Orderscommodity orderscommodity = new Orderscommodity(orders1.getOrderDate(), orders1.getOrderId(), commodity.getCommodityId(), orders1.getCostomerPhone(), commodity.getCommodityName(), commodity.getCommodityPrice(), ordersTails1.getCommodityQuantity());
                    orderscommodities.add(orderscommodity);
                }
            }
            if (orderscommodities.isEmpty()) {

                return null;// 处理orderscommodities为空的情况
            }
            return orderscommodities;
        } catch (Exception e) {
            throw new RuntimeException("Error querying goods", e);
        }
    }




    // 订单的删除
    @DeleteMapping("/delete/{orderId}")
    public Result deleteOrder(@PathVariable("orderId") Long orderId) {
        try {
            Orders order = ordersMapper.selectById(orderId);
            if (order != null) {
                ordersMapper.deleteById(orderId);
                QueryWrapper<OrdersTails> querywrapper = new QueryWrapper<>();
                querywrapper.eq("order_id", orderId);
                int rows = ordersTailsMapper.delete(querywrapper);
                return Result.success();
            } else {
                return Result.error();
            }
        } catch (Exception e) {
            // 处理异常，例如记录日志或返回错误信息
            return Result.error();
        }
    }

//    @DeleteMapping("/deletebyid")
//    public ResponseEntity<String> deleteOrders(@RequestParam List<Long> orderIds, @RequestParam List<Long> commodityIds) {
//        if (orderIds.size() != commodityIds.size()) {
//            return ResponseEntity.badRequest().body("订单ID和商品ID的数量不匹配");
//        }
//
//        for (int i = 0; i < orderIds.size(); i++) {
//            Long orderId = orderIds.get(i);
//            Long commodityId = commodityIds.get(i);
//
//            QueryWrapper<OrdersTails> queryWrapper = new QueryWrapper<>();
//            queryWrapper.eq("order_id", orderId).eq("commodity_id", commodityId);
//            OrdersTails ordersTails = ordersTailsMapper.selectOne(queryWrapper);
//            ordersTailsMapper.delete(queryWrapper);
//
//            Orders orders = ordersMapper.selectById(orderId);
//            Commodity commodity = commodityMapper.selectById(commodityId);
//
//            if (orders != null && commodity != null && ordersTails != null) {
//                orders.setOrderPrice(orders.getOrderPrice().subtract(commodity.getCommodityPrice().multiply(new BigDecimal(ordersTails.getCommodityQuantity()))));
//                ordersMapper.updateById(orders);
//            } else {
//                return ResponseEntity.status(HttpStatus.NOT_FOUND).body("订单或商品不存在");
//            }
//        }
//
//        return ResponseEntity.ok("订单删除成功");
//    }


    @DeleteMapping("/delete")
    public Result deleteOrder(@RequestBody Orderscommodity orderscommodity){
        QueryWrapper<OrdersTails> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", orderscommodity.getOrderId()).eq("commodity_id", orderscommodity.getCommodityId());
        OrdersTails ordersTails = ordersTailsMapper.selectOne(queryWrapper);
        ordersTailsMapper.delete(queryWrapper);
        Orders orders = ordersMapper.selectById(orderscommodity.getOrderId());
        Commodity commodity = commodityMapper.selectById(orderscommodity.getCommodityId());

        if (orders != null && commodity != null && ordersTails != null) {
            orders.setOrderPrice(orders.getOrderPrice().subtract(commodity.getCommodityPrice().multiply(new BigDecimal(ordersTails.getCommodityQuantity()))));
            ordersMapper.updateById(orders);
            return Result.success();
        } else {
            return Result.error("订单不存在");
        }
    }

}
